package com.writing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.writing.entity.WorldSetting;
import com.writing.mapper.WorldSettingMapper;
import com.writing.service.WorldSettingService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 世界观设定Service实现类
 */
@Service
public class WorldSettingServiceImpl extends ServiceImpl<WorldSettingMapper, WorldSetting> implements WorldSettingService {

    @Override
    public List<WorldSetting> getWorldSettingsByNovelId(Long novelId) {
        return this.list(new LambdaQueryWrapper<WorldSetting>()
                .eq(WorldSetting::getNovelId, novelId)
                .orderByAsc(WorldSetting::getId));
    }

    @Override
    public WorldSetting getWorldSettingById(Long worldSettingId, Long novelId) {
        return this.getOne(new LambdaQueryWrapper<WorldSetting>()
                .eq(WorldSetting::getId, worldSettingId)
                .eq(WorldSetting::getNovelId, novelId));
    }

    @Override
    public WorldSetting createWorldSetting(WorldSetting worldSetting) {
        // 设置默认分类
        if (worldSetting.getCategory() == null) {
            worldSetting.setCategory("setting");
        }

        this.save(worldSetting);
        return worldSetting;
    }

    @Override
    public WorldSetting updateWorldSetting(WorldSetting worldSetting) {
        // 验证世界观设定是否存在
        WorldSetting existingWorldSetting = this.getOne(new LambdaQueryWrapper<WorldSetting>()
                .eq(WorldSetting::getId, worldSetting.getId())
                .eq(WorldSetting::getNovelId, worldSetting.getNovelId()));

        if (existingWorldSetting == null) {
            throw new RuntimeException("世界观设定不存在");
        }

        this.updateById(worldSetting);
        return worldSetting;
    }

    @Override
    public boolean deleteWorldSetting(Long worldSettingId, Long novelId) {
        WorldSetting worldSetting = getWorldSettingById(worldSettingId, novelId);
        if (worldSetting == null) {
            throw new RuntimeException("世界观设定不存在");
        }

        return this.removeById(worldSettingId);
    }
}
